﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Bordspil.Models
{
    public class AppRepository : IAppRepository
    {
        private AppDataContext db = new AppDataContext();   

        public IEnumerable<User> GetAllUsers()
        {
            return db.user;
        }

        public IEnumerable<Deck> GetAllCards()
        {
            return db.card;
        }

        public IEnumerable<GameInstance> GetAllGames()
        {
            return db.gameInst;
        }

        public IEnumerable<DecksForGames> GetAllCardsForInstance()
        {
            return db.cardsForGame;
        }

        public IEnumerable<LudoImg> GetAllImages()
        {
            return db.pedImageUrl;
        }

        public void AddUser(User user)
        {
            var crypto = new SimpleCrypto.PBKDF2();

            var encryptPW = crypto.Compute(user.password);

            var newUser = db.user.Create();

            newUser.name = user.name;
            newUser.password = encryptPW;
            newUser.passwordSalt = crypto.Salt;
            newUser.username = user.username;
            newUser.email = user.email;
            newUser.birthdate = user.birthdate;
            newUser.gender = user.gender;
            newUser.profilePoints = 0;
            newUser.playerStatus = 0;
            newUser.connectID = null;

            db.user.Add(newUser);
            db.SaveChanges();
        }

        public void AddGameInstance(GameInstance game)
        {
            db.gameInst.Add(game);
            db.SaveChanges();
        }

        public void EditUser(User user)
        {
            db.SaveChanges();
        }

        public void AddDeckToInstance(List<Deck> deck)
        {
            var instance = (from x in db.gameInst
                            select x).ToList();

            GameInstance inst = instance.LastOrDefault();

            for (int i = 0; i < 24; i++)
            {
                var card = db.cardsForGame.Create();

                card.DeckOfCardsID = deck[i].ID;
                card.Status = 1;  //1 = facedown, and is the default psosition
                card.GameInstID = inst.ID;

                db.cardsForGame.Add(card);
                db.SaveChanges();
            }
        }

        public void SaveCard(DecksForGames card)
        {
            db.SaveChanges();
        }

        public void SavePed(List<LudoImg> ped)
        {
            db.SaveChanges();
        }
    }
}